package com.bitcat.firstapp.demo.servicedemo

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log

class MyService : Service() {
    private val TAG = "MyService"

    //  计数器
    private var count = 0
    // 计数器是否在计数
    private var isRunning = false

    private val handler = Handler(Looper.getMainLooper())

    private val runnable = object : Runnable {
        override fun run() {
            count++
            Log.d(TAG, "计数：$count")
            handler.postDelayed(this, 1000)
        }
    }

    private val binder = MyBinder()

    inner class MyBinder: Binder() {
        fun getService():MyService = this@MyService
    }


    override fun onBind(intent: Intent): IBinder {
        Log.d(TAG, "onBind: ")
        return binder
    }

    override fun onCreate() {
        Log.d(TAG, "onCreate: ")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand: ")
        startCount()
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.d(TAG, "onUnbind: ")
        return super.onUnbind(intent)
    }

    // 开始计数
    private fun startCount() {
        if (isRunning) return
        isRunning = true
        handler.post(runnable)
    }

    // 停止计数
    private fun stopCount(){
        isRunning = false
        handler.removeCallbacks(runnable)
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy: ")
        stopCount()
        super.onDestroy()
    }

    fun getCount() = count
}